<?php
namespace Home\Controller;
use Think\Controller;
class DatabaseController extends CommonController {
    /*
     * 数据库控制器
     * 
     * ******************  该用户下的数据库罗列
     */
    public function index(){

        if(IS_GET){

            $map['mid'] = session('mid');
            $DB = M('database');
            /**
            数据分页显示开始
            **/
            $count      = $DB->where($map)->count();// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $Page->lastSuffix=false;
                        $Page->setConfig('header','<li class="rows">共<b>%TOTAL_ROW%</b>条记录&nbsp;&nbsp;每页<b>20</b>条&nbsp;&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</li>');
                        $Page->setConfig('prev','上一页');
                        $Page->setConfig('next','下一页');
                        $Page->setConfig('last','末页');
                        $Page->setConfig('first','首页');
                        $Page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
            $show       = $Page->show();// 分页显示输出
            // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
            $list = $DB->where($map)->limit($Page->firstRow.','.$Page->listRows)->select();
            /**
            数据分页结束
            **/

            $this->assign('list',$list);
            $this->assign('show',$show);
            $this->display();
        }
    }
    
    
    /*
     * ******************   功能有：
     * 1. 数据库的新建
     * 2. 数据库的名称修改
     * 3. 数据库的删除
     * 4. 用户和数据库的关联关系（写着common 控制器才对）
     * 5. 
     */
    
    /**
     * 添加数据库功能
     */
    public function add(){

        if(IS_GET){

            $this->display();
        }else{

            $DB = M('database');
            $data['mid'] = session('mid');
            $data['db_name'] = trim(I('post.db_name'));
            $data['db_name_ch'] = trim(I('post.db_name_ch'));
            $data['db_encoding'] = trim(I('post.db_encoding'));
            $data['ctime'] = I('server.REQUEST_TIME');

            $re = $DB->data($data)->add();
            if(!empty($re)){

                $this->success('添加成功!',U('Home/Database/index'),1);
            }else{

                $this->error('添加失败!','',1);
            }
        }
    }


    /**
     * ajax删除数据库
     */
    public function del_database(){

        $map['dbid'] = I('post.dbid');
        $map['mid'] = session('mid');
        // print_r($map); die;
        $DB = M('database');

        $re = $DB->where($map)->delete();
        if($re){
            echo json_encode(1);
        }else{
            echo json_encode(0);
        }
    }


    /**
     * 修改数据库表
     */
    public function modify(){

        if(IS_GET){

            $map['dbid'] = I('get.dbid');
            $map['mid'] = session('mid');

            $DB = M('database');
            $list = $DB->where($map)->find();

            $this->assign('list',$list);
            $this->display();
        }else{

            $map['dbid'] = I('post.dbid');
            $map['mid'] = session('mid');

            $data['db_name'] = trim(I('post.db_name'));
            $data['db_name_ch'] = trim(I('post.db_name_ch'));
            $data['db_encoding'] = trim(I('post.db_encoding'));

            $DB = M('database');

            $re = $DB->where($map)->data($data)->save();

            if($re){

                $this->success('修改成功!',U('Home/Database/index'),1);
            }else{

                $this->error('修改失败!','',1);
            }
        }
    }



    /**
        数据库数据表
    **/
    public function tables(){

        if(IS_GET){

            $map['dbid'] = I('get.dbid');
            $map['mid'] = session('mid');

            $DB = M('table');

            $list = $DB->where($map)->select();

            /**
             * 页面链接地址
             */
            $db_url = 'http://'.$_SERVER['HTTP_HOST'].U('Home/Database/index');
            $table_url = 'http://'.$_SERVER['HTTP_HOST'].U('Home/Database/tables',array('dbid' => $map['dbid']));
            // echo $table_url; die;
            $this->assign('dbid',$map['dbid']);
            $this->assign('list',$list);
            $this->display();
        }
    }


    /**
     * 添加新的数据表
     */
    public function add_table(){

        if(IS_GET){

            $dbid = I('get.dbid');

            $this->assign('dbid',$dbid);
            $this->display();
        }else{

            $data['dbid'] = I('post.dbid');
            $data['mid'] = session('mid');
            $data['tb_name'] = trim(I('post.tb_name'));
            $data['tb_name_ch'] = trim(I('post.tb_name_ch'));
            $data['engine'] = I('post.engine');
            $data['tb_encoding'] = I('post.tb_encoding');
            // print_r($data); die;
            $DB = M('table');

            $re = $DB->data($data)->add();
            if(!empty($re)){

                $this->success('添加成功!',U('Home/Database/tables',array('dbid' => $data['dbid'])),1);
            }else{

                $this->error('添加失败!','',1);
            }
        }
    }



    /**
     * ajax删除数据表
     */
    
    public function del_table(){

        if(IS_AJAX){

            $map['dbid'] = I('post.dbid');
            $map['tbid'] = I('post.tbid');
            $map['mid'] = session('mid');
            $DB = M('table');

            $re = $DB->where($map)->delete();
            if($re){

                echo json_encode(1);
            }else{

                echo json_encode(0);
            }
        }
    }


    /**
     * 修改数据表
     */
    public function modify_table(){

        if(IS_GET){

            $map['mid'] = session('mid');
            $map['dbid'] = I('get.dbid');
            $map['tbid'] = I('get.tbid');
            // print_r($map); die;
            $DB = M('table');

            $list = $DB->where($map)->find();

            $this->assign('list',$list);
            $this->display();
        }else{

            $map['dbid'] = I('post.dbid');
            $map['tbid'] = I('post.tbid');
            $map['mid'] = session('mid');

            $data['tb_name'] = trim(I('post.tb_name'));
            $data['tb_name_ch'] = trim(I('post.tb_name_ch'));
            $data['engine'] = I('post.engine');
            $data['tb_encoding'] = I('post.tb_encoding');

            $DB = M('table');

            $re = $DB->where($map)->data($data)->save();

            if($re){

                $this->success('修改成功!',U('Home/Database/tables',array('dbid' => $map['dbid'])),1);
            }else{

                $this->error('修改失败!','',1);
            }
        }
    }


    /**
     * ajax获取表下面的所有字段
     */
    public function show_fields(){

        if(IS_AJAX){

            $map['dbid'] = I('post.dbid');
            $map['tbid'] = I('post.tbid');
            $map['mid'] = session('mid');

            $DB_table = M('table');
            $re = $DB_table->where($map)->find();
            if($re){

                $DB_table_field_relationship = M('table_field_relationship');

                $list = $DB_table_field_relationship->where(array('tbid' => $map['tbid']))->select();
                $DB_field = M('field');
                foreach ($list as $key => $value) {
                    # code...
                    $result[$key] = $DB_field->where(array('flid' => $value['flid']))->find();
                    if(empty($result[$key])){
                        unset($result[$key]);
                    }
                }
            }else{
                $result = 0;
                echo json_encode($result);
            }
            /**
             * 循环替换result中的值
             */
            foreach ($result as $key => $value) {
                # code...
                if($value['iskey'] == 1){
                    $result[$key]['iskey'] = '是';
                }else{

                    $result[$key]['iskey'] = '否';
                }
                if($value['isunsigned'] == 1){
                    $result[$key]['isunsigned'] = 'unsigned';
                }else{

                    $result[$key]['isunsigned'] = 'signed';
                }
                if($value['extra_value'] == 1){
                    $result[$key]['extra_value'] = '是';
                }else{

                    $result[$key]['extra_value'] = '否';
                }
                $result[$key]['ctime'] = date('Y-m-d H:i:s',$value['ctime']);
            }

            echo json_encode($result);
        }
    }


    /**
     * 获取表下面的所有字段
     */
    public function view_fields(){

        if(IS_GET){

            $map['dbid'] = I('get.dbid');
            $map['tbid'] = I('get.tbid');
            $map['mid'] = session('mid');

            $DB_table = M('table');
            $re = $DB_table->where($map)->find();

            if($re){

                $DB_table_field_relationship = M('table_field_relationship');

                $list = $DB_table_field_relationship->where(array('tbid' => $map['tbid'],'mid' => $map['mid']))->order('rank asc')->select();
                // print_r($list); die;
                $DB_field = M('field');
                foreach ($list as $key => $value) {
                    # code...
                    $result[$key] = $DB_field->where(array('flid' => $value['flid']))->find();
                    $result[$key]['rank'] = $value['rank']; 
                    $result[$key]['id'] = $value['id']; 
                }
            }
            // print_r($result); die;
            $this->assign('dbid',$map['dbid']);
            $this->assign('tbid',$map['tbid']);
            $this->assign('list',$result);
            $this->display();
        }
    }


    /**
     * 删除表中已有的字段
     */
    public function del_field(){

        if(IS_AJAX){

            $map['flid'] = I('post.flid');
            $map['tbid'] = I('post.tbid');
            $map['mid'] = session('mid');

            $DB = M('table_field_relationship');

            $re = $DB->where($map)->delete();

            if($re){

                echo json_encode(1);
            }else{

                echo json_encode(0);
            }
        }
    }


    /**
     * 通过关键字搜索用户创建的字段
     */
    public function select_keywords_fields(){

        if(IS_AJAX){

            $map['mid'] = session('mid');
            $fl_name = I('post.select_keywords');
            $select_like = '%'.$fl_name.'%';
            $map['fl_name'] = array('like',$select_like);

            $DB = M('field');

            $result = $DB->where($map)->select();
            // print_r($result); die;
            echo json_encode($result); 
        }
    }


    /**
     * ajax动态添加字段
     */
    public function add_fields_for_table(){

        if(IS_AJAX){

            $data['flid'] = I('post.flid');
            $data['tbid'] = I('post.tbid');
            $data['mid'] = session('mid');
            $data['ctime'] = I('server.REQUEST_TIME');
            $DB = M('table_field_relationship');
            /**
             * 计算当前数据表包含字段个数，新加入的rank最大
             */
            $field_count_num = $DB->where(array('mid' => $data['mid'],'tbid' => $data['tbid']))->count();
            if(empty($field_count_num)){
                $data['rank'] = 0;
            }else{
                $data['rank'] = $field_count_num;
            }
            // print_r($data); die;
            
            $repeat = $DB->where(array('mid' => $data['mid'],'tbid' => $data['tbid'],'flid' => $data['flid']))->find();
            if($repeat){

                echo json_encode(2);
            }else{

                $re = $DB->data($data)->add();
                if(!empty($re)){

                echo json_encode(1);
                }else{

                    echo json_encode(0);
                }
            }
            
        }
    }


    /**
     * 更新字段的rank 拖动ajax更新排序
     */
    public function update_rank(){

        if(IS_AJAX){
            // echo 1; die;
            $new_rank_arr = I('post.new_rank_arr');
            $map['tbid'] = I('post.tbid');
            $map['mid'] = session('mid');
            // print_r($map); die;
            $DB = M('table_field_relationship');
            // print_r($new_rank_arr); die;
            $res_code = True;
            foreach ($new_rank_arr as $key => $value) {
                # code...
                $re = $DB->where(array('id' => $value[0],'tbid' => $map['tbid'],'mid' => $map['mid']))->data(array('rank' => $value[1]))->save();
                if($re)
                {
                    $res_code = True;
                }
                else{
                    $res_code = false;
                }
            }

            if($res_code){

                echo json_encode(1);
            }
        }
    }
}
